package com.ruoyi.project.exam.controller;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.Handle;
import com.ruoyi.common.constant.QuType;
import com.ruoyi.common.utils.IdGen;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.domain.AjaxResult.Type;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.exam.domain.QuAnswerModel;
import com.ruoyi.project.exam.domain.QuModel;
import com.ruoyi.project.exam.domain.RepoModel;
import com.ruoyi.project.exam.service.IQuService;
import com.ruoyi.project.exam.service.IRepoService;
/**
 * 试题管理
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/exam/qu")
public class QuController extends BaseController{
	
	private String prefix = "exam/qu";
	@Autowired
	private IQuService quService;
	
	@Autowired
	private IRepoService repoService;
	
	@RequiresPermissions("exam:qu:view")
	@GetMapping()
	public String qu(ModelMap mmap) {
		List<RepoModel> repoList = repoService.selectAll();
		mmap.put("repoList", repoList);
		return prefix + "/qu";
	}

	/**
	 * 查询列表
	 */
	@RequiresPermissions("exam:qu:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(QuModel model) {
		startPage();
		List<QuModel> list = quService.selectQuList(model);
		return getDataTable(list);
	}
	
	/**
	 * 新增
	 */
	
	@GetMapping("/add")
	public String add(@RequestParam(value="repoId", required=false)String id,ModelMap mmap) {
		mmap.put("repoId", id);
		List<RepoModel> repoList = repoService.selectAll();
		mmap.put("repoList", repoList);
		return prefix + "/add";
	}
	
	/**
	 * 新增保存
	 */
	@RequiresPermissions("exam:qu:add")
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(QuModel model) {
		try{
			quService.insertQu(model);
			return toAjax(Handle.SUCCESS.getCode());
		}catch(Exception e){
			e.printStackTrace();
		}
		return toAjax(Handle.FAIL.getCode());
	}
	
	/**
	 * 修改
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") String id, ModelMap mmap) {
		mmap.put("model", quService.selectQuById(id));
		List<RepoModel> repoList = repoService.selectAll();
		mmap.put("repoList", repoList);
		return prefix + "/edit";
	}
	
	/**
	 * 修改保存
	 */
	@RequiresPermissions("exam:qu:edit")
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(QuModel model) {
		try{
			quService.updateQu(model);
			return toAjax(Handle.SUCCESS.getCode());
		}catch(Exception e){
			e.printStackTrace();
		}
		return toAjax(Handle.FAIL.getCode());
	}
	
	/**
	 * 删除
	 */
	@RequiresPermissions("exam:qu:remove")
	@PostMapping("/remove")
	@ResponseBody
	public AjaxResult remove(String ids) {
		return toAjax(quService.deleteQuByIds(ids));
	}
	
	/**
	 * 导入
	 */
	@GetMapping("/importExcel")
	public String importExcel(@RequestParam(value="repoId", required=false)String id, ModelMap mmap) {
		List<RepoModel> repoList = repoService.selectAll();
		mmap.put("repoList", repoList);
		return prefix + "/importExcel";
	}
	
	@PostMapping("/importData")
	@ResponseBody
	public AjaxResult importData(@RequestParam(value="repoId", required=true)String repoId,
			@RequestParam(value="file", required=true)MultipartFile file) {
		String errMsg = "";
		String filePath ="";
		Workbook wb = null;
		Sheet sheet= null;
		int sheetIndex = 0;
		int rowIndex = 0;
		List<QuModel> quList = new ArrayList<QuModel>();
		List<QuAnswerModel> quAnswerList = new ArrayList<QuAnswerModel>();
		try{
			if(file == null || file.isEmpty()){
				errMsg = "上传文件不能为空！";
				throw new RuntimeException(errMsg);
			}
			String[] selectTitle={"序号","试题题目","选项内容A","选项内容B","选项内容C","选项内容D","试题答案","答案解析"};
			String[] judgeTitle={"序号","试题题目","试题答案","答案解析"};
			wb = WorkbookFactory.create(file.getInputStream());
			for(int i = 0; i < wb.getNumberOfSheets(); i++){
				sheetIndex = i+1;
				sheet = wb.getSheetAt(i);
				if(i==0&& !"单选题".equals(sheet.getSheetName())){
					errMsg = "excel解析出错：请核对第【"+sheetIndex+"】个Sheet页名称！";
					throw new RuntimeException(errMsg);
				}
				if(i==1&& !"多选题".equals(sheet.getSheetName())){
					errMsg = "excel解析出错：请核对第【"+sheetIndex+"】个Sheet页名称！";
					throw new RuntimeException(errMsg);
				}
				if(i==2&& !"判断题".equals(sheet.getSheetName())){
					errMsg = "excel解析出错：请核对第【"+sheetIndex+"】个Sheet页名称！";
					throw new RuntimeException(errMsg);
				}
				int rows= sheet.getLastRowNum()+1;
				if(rows > 0){
					Row head = sheet.getRow(0);
					String[] headArr = new String[head.getPhysicalNumberOfCells()];
					for(int y = 0; y<head.getPhysicalNumberOfCells(); y++){
						String headStr = String.valueOf(getCellValue(head.getCell(y)));
						if(StringUtils.isNotBlank(headStr)){
							headStr = headStr.trim();
						}
						headArr[y] = headStr;
					}
				
					String[] title = (i==2?judgeTitle:selectTitle);
					boolean flag = validateHead(headArr, title);
					if(!flag){
						errMsg = "excel解析出错：请核对【"+sheetIndex+"】个Sheet页标题！";
						throw new RuntimeException(errMsg);		
					}
					for(int y = 1; y< rows; y++){
						rowIndex = y+1;
						Row r = sheet.getRow(y);
						if(i==0 || i== 1){
							String seq = String.valueOf(getCellValue(r.getCell(0)));
							String content = String.valueOf(getCellValue(r.getCell(1)));
							String ansA = String.valueOf(getCellValue(r.getCell(2)));
							String ansB = String.valueOf(getCellValue(r.getCell(3)));
							String ansC = String.valueOf(getCellValue(r.getCell(4)));
							String ansD = String.valueOf(getCellValue(r.getCell(5)));
							String ansRight = String.valueOf(getCellValue(r.getCell(6)));
							String analysis = String.valueOf(getCellValue(r.getCell(7)));
							if(StringUtils.isNotBlank(content)&&StringUtils.isNotBlank(ansA)&&StringUtils.isNotBlank(ansB)&&StringUtils.isNotBlank(ansC)&&
									StringUtils.isNotBlank(ansD)&&StringUtils.isNotBlank(ansRight)){
								QuModel quModel = new QuModel();
								quModel.setId(IdGen.uuid());
								if(i==0){
									quModel.setQuType(QuType.RADIO.getType());
								}
								if(i ==1 ){
									quModel.setQuType(QuType.MULTI.getType());
								}
								quModel.setContent(content);
								quModel.setAnalysis(analysis);
								quModel.setCreateTime(new Date());
								quModel.setCreateBy(ShiroUtils.getLoginName());
								QuAnswerModel answerModelA  = new QuAnswerModel();
								answerModelA.setId(IdGen.uuid());
								answerModelA.setContent(ansA);
								answerModelA.setSort(0);
								answerModelA.setQuId(quModel.getId());
								QuAnswerModel answerModelB  = new QuAnswerModel();
								answerModelB.setId(IdGen.uuid());
								answerModelB.setContent(ansB);
								answerModelB.setSort(1);
								answerModelB.setQuId(quModel.getId());
								QuAnswerModel answerModelC  = new QuAnswerModel();
								answerModelC.setId(IdGen.uuid());
								answerModelC.setContent(ansC);
								answerModelC.setSort(2);
								answerModelC.setQuId(quModel.getId());
								QuAnswerModel answerModelD  = new QuAnswerModel();
								answerModelD.setId(IdGen.uuid());
								answerModelD.setContent(ansD);
								answerModelD.setSort(3);
								answerModelD.setQuId(quModel.getId());
								char[] ansArr = ansRight.trim().toCharArray();
								for(int j = 0; j < ansArr.length; j++){
									String ans = String.valueOf(ansArr[j]);
									if("AaBbCcDd".indexOf(ans) > -1){
										if("A".equals(ans) || "a".equals(ans)){
											answerModelA.setIsRight(true);
										}
										if("B".equals(ans) || "b".equals(ans)){
											answerModelB.setIsRight(true);							
										}
										if("C".equals(ans) || "c".equals(ans)){
											answerModelC.setIsRight(true);
										}
										if("D".equals(ans) || "d".equals(ans)){
											answerModelD.setIsRight(true);
										}
									}else{
										errMsg = "excel解析出错：请核对【"+sheetIndex+"】个Sheet页,第【"+rowIndex+"】行题答案填写是否准确！";
										throw new RuntimeException(errMsg);	
									}
								}
								quAnswerList.add(answerModelA);
								quAnswerList.add(answerModelB);
								quAnswerList.add(answerModelC);
								quAnswerList.add(answerModelD);
								quList.add(quModel);
							}else if(StringUtils.isBlank(content)&&StringUtils.isBlank(ansA)&&StringUtils.isBlank(ansB)&&StringUtils.isBlank(ansC)&&
									StringUtils.isBlank(ansD)&&StringUtils.isBlank(ansRight)){
								continue;
							}else{
								errMsg = "excel解析出错：请核对【"+sheetIndex+"】个Sheet页,第【"+rowIndex+"】行题填写是否准确！";
								throw new RuntimeException(errMsg);	
							}
						}
						if(i== 2){
							String seq = String.valueOf(getCellValue(r.getCell(0)));
							String content = String.valueOf(getCellValue(r.getCell(1)));
							String ansRight = String.valueOf(getCellValue(r.getCell(2)));
							String analysis = String.valueOf(getCellValue(r.getCell(3)));
							if(StringUtils.isNotBlank(content) && StringUtils.isNotBlank(ansRight)){
								QuModel quModel = new QuModel();
								quModel.setId(IdGen.uuid());
								quModel.setQuType(QuType.JUDGE.getType());
								quModel.setContent(content);
								quModel.setAnalysis(analysis);
								quModel.setCreateTime(new Date());
								quModel.setCreateBy(ShiroUtils.getLoginName());
								if("正确".equals(ansRight.trim())|| "错误".equals(ansRight.trim()) ){
									QuAnswerModel answerModelA  = new QuAnswerModel();
									answerModelA.setId(IdGen.uuid());
									answerModelA.setContent("正确");
									answerModelA.setSort(0);
									answerModelA.setQuId(quModel.getId());
									answerModelA.setIsRight("正确".equals(ansRight.trim()));
									QuAnswerModel answerModelB  = new QuAnswerModel();
									answerModelB.setId(IdGen.uuid());
									answerModelB.setContent("错误");
									answerModelB.setSort(1);
									answerModelB.setQuId(quModel.getId());
									answerModelB.setIsRight("错误".equals(ansRight.trim()));
									quAnswerList.add(answerModelA);
									quAnswerList.add(answerModelB);
									quList.add(quModel);
								}else{
									errMsg = "excel解析出错：请核对【"+sheetIndex+"】个Sheet页,第【"+rowIndex+"】行题答案填写是否准确！";
									throw new RuntimeException(errMsg);	
								}
							}else if(StringUtils.isBlank(content) && StringUtils.isBlank(ansRight)){
								continue;
							}else{
								errMsg = "excel解析出错：请核对【"+sheetIndex+"】个Sheet页,第【"+rowIndex+"】行题填写是否准确！";
								throw new RuntimeException(errMsg);	
							}
						}
					}
				}
			}
			filePath = FileUploadUtils.upload(RuoYiConfig.getQuPath(), file);
			if(StringUtils.isNotBlank(filePath)){
				filePath = filePath.replace(Constants.RESOURCE_PREFIX,"");
			}
			if(quList != null && !quList.isEmpty()){
				quService.importQu(repoId, quList, quAnswerList);
			}
			return new AjaxResult(Type.SUCCESS, "试题导入成功！");
		}catch(Exception e){
			if(StringUtils.isBlank(errMsg)){
				errMsg = "试题导入失败！";
			}
			if(StringUtils.isNotBlank(filePath)){
				try {
					FileUtils.delete(new File(RuoYiConfig.getQuPath()+filePath));
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			logger.error("试题导入失败："+e.getMessage());
		}
		return new AjaxResult(Type.ERROR, errMsg);
	}
	
	private boolean validateHead(String[] validateTitle, String[] title){
		if(validateTitle != null && validateTitle.length > 0&& validateTitle.length>= title.length){
			for(int i = 0; i < title.length; i++){
				if(!title[i].equals(validateTitle[i])){
					return false;
				}
			}
			return true;
		}
		return false;
	}
	@SuppressWarnings("deprecation")
	private Object getCellValue(Cell cell){
		Object val = "";
		if(cell != null){
			if(cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum()  == CellType.FORMULA){
				val = cell.getNumericCellValue();
				if(HSSFDateUtil.isCellDateFormatted(cell)){
					val= DateUtil.getJavaDate((Double)val);
				}else{
					if((Double)val %1 > 0){
						val = new DecimalFormat("0.00").format(val);
					}else{
						val = new DecimalFormat("0").format(val);
					}
				}
			}else  if(cell.getCellTypeEnum() == CellType.STRING){
				val = cell.getStringCellValue();
			}else  if(cell.getCellTypeEnum() == CellType.BOOLEAN){
				val = cell.getBooleanCellValue();
			}else  if(cell.getCellTypeEnum() == CellType.ERROR){
				val = cell.getErrorCellValue();
			}
		}
		return val;
	}
	
}
